package com.record.utils;

import com.elite.groovy.kh.KHDBConfig;
import com.elite.groovy.kh.KHUtil;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.UUID;

public class RecUtils extends HttpServlet {
    private static final Log log = LogFactory.getLog(RecUtils.class);
    private static JSONObject rec_Config = new JSONObject();
    private static String amrconvertcmd = "";
    private static String tempdir = "";
    private static String debugconvert = "";
    public static String ProxyIP = "";
    public static String ProxyPort = "";

    public static String ConvertAmrAudio(JdbcTemplate jt, HttpServletResponse response, String entId, String recfileurl) {
        log.debug("ConvertAmrAudio amr file is " + recfileurl);

        String res_AudioFile = "";

        // 初始化参数
        rec_Config = KHUtil.SFIsNull(rec_Config.toString()) ? JSONObject.fromObject(KHDBConfig.getParamConfig(jt, "REC_CFG-" + entId)) : rec_Config;

        tempdir = KHUtil.GetSFJV(rec_Config, "tempdir");
        amrconvertcmd = KHUtil.GetSFJV(rec_Config, "amrconvertcmd");
        debugconvert = KHUtil.GetSFJV(rec_Config, "debugconvert");
        ProxyIP = KHUtil.GetSFJV(rec_Config, "ProxyIP");
        ProxyPort = KHUtil.GetSFJV(rec_Config, "ProxyPort");

        String amrfilename = tempdir + UUID.randomUUID().toString() + ".amr";
        String wavfilename = tempdir + UUID.randomUUID().toString() + ".wav";
        try {
            log.debug("temp amr file is " + amrfilename);
            HttpHelper helper = new HttpHelper();
            log.debug("begin download amr file from " + recfileurl);

            try {
                HashMap<String, String> headers = new HashMap<String, String>();
                if (helper.DoHttpGetFileRequest(recfileurl, headers, "UTF-8", amrfilename, ProxyIP, ProxyPort)) {
                    log.debug("amr file downloaded");

                    // ffmpeg方式
                    if (amrconvertcmd.contains("ffmpeg")) {
                        String cmd = amrconvertcmd.replace("${amrfile}", amrfilename).replace("${wavfile}", wavfilename);
                        log.debug("amr convert cmd is " + cmd);
                        if (runcmd(cmd, true)) {
                            writeToReponse(response, wavfilename);
                        } else {
                            throw new RuntimeException("convert amr file failed");
                        }
                    } else {
                        if (RecordEncode.audioEncode(amrfilename, wavfilename)) {
                            log.debug("audio(amr) Encode end");

                        } else {
                            throw new RuntimeException("audio(amr) Encode failed");
                        }
                    }

                } else {
                    log.error("download amr file failed");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } finally {
            if (!debugconvert.equals("true")) {
                File f = new File(amrfilename);
                if ((f.exists()) && (f.isFile())) {
                    f.delete();
                }
                f = new File(wavfilename);
                if ((f.exists()) && (f.isFile()))
                    f.delete();
            }
        }
        return res_AudioFile;
    }

    private static boolean runcmd(String cmd, boolean readoutput) {
        boolean ret = false;
        if (cmd.equals(""))
            return true;
        try {
            log.debug("begin run cmd " + cmd);
            Process process = Runtime.getRuntime().exec(cmd);
            if (readoutput) {
                final InputStream is1 = process.getInputStream();

                final InputStream is2 = process.getErrorStream();

                new Thread() {
                    public void run() {
                        BufferedReader br1 = new BufferedReader(new InputStreamReader(is1));
                        try {
                            String line1 = null;
                            while ((line1 = br1.readLine()) != null)
                                ;
                        } catch (IOException e) {
                            log.error("", e);
                            try {
                                is1.close();
                            } catch (IOException e1) {
                                log.error("", e);
                            }
                        } finally {
                            try {
                                is1.close();
                            } catch (IOException e) {
                                log.error("", e);
                            }
                        }
                    }
                }.start();

                new Thread() {
                    public void run() {
                        BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
                        try {
                            String line2 = null;
                            while ((line2 = br2.readLine()) != null)
                                ;
                        } catch (IOException localIOException) {
                            try {
                                is2.close();
                            } catch (IOException localIOException1) {
                            }
                        } finally {
                            try {
                                is2.close();
                            } catch (IOException localIOException2) {
                            }
                        }
                    }
                }.start();
            }
            int exitcode = process.waitFor();
            if (exitcode == 0) {
                log.debug("run " + cmd + " successfully");
                ret = true;
            } else {
                log.debug("run " + cmd + " failed and return " + exitcode);
            }
            process.getInputStream().close();
            process.getOutputStream().close();
            process.getErrorStream().close();
            process.destroy();
        } catch (Exception ie) {
            log.error("", ie);
        }
        return ret;
    }

    private static void writeToReponse(HttpServletResponse response, String filename) throws IOException {
        response.setHeader("Content-Type", "audio/x-wav");
        File file = new File(filename);
        int len_l = (int) file.length();
        response.setHeader("Content-Length", String.valueOf(len_l));
        response.setHeader("Accept-Ranges", "bytes");
        byte[] buf = new byte[2048];
        FileInputStream fis = null;
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            fis = new FileInputStream(file);
            len_l = fis.read(buf);
            while (len_l != -1) {
                out.write(buf, 0, len_l);
                len_l = fis.read(buf);
            }
            out.flush();
        } finally {
            if (out != null) {
                out.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }

}